let {
  dboption,
  webport,
  webroot,
  _dyfwlayers,
  _importformat,
} = require("./conf");
var { Sequelize, DataTypes } = require("sequelize");
const sequelize = new Sequelize(dboption[process.argv[2] ?? "dev"]);
global.sequelize = sequelize;
global.DataTypes = DataTypes;

const express = require("express");
const app = express();
var history = require("connect-history-api-fallback");
// app.use(history());

global.app = app;
const uploadDir = webroot + "\\img";
app.use(
  express.static(webroot, {
    setHeaders: (res) => {
      res.set("Access-Control-Allow-Origin", "*");
    },
  })
);

app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == "options") res.sendStatus(200);
  else next();
});
app.use(express.json({ limit: "2100000kb" })); // for parsing application/json
app.use(express.urlencoded({ limit: "2100000kb", extended: true }));

// require("./rt_base_projectdetails");
// require("./rt_base_bidinfo");
// require("./rt_base_conpermit");
require("./rt_ids");
app.listen(webport, () => {
  console.log(`Example app listening at http://localhost:${webport}`);
});

const multer = require("multer");
const path = require("path");
const upload = multer({ dest: "/project/city-node/uploads/" });
const JSZip = require("jszip");
const fs = require("fs");
// const gdal = require("gdal");
const esriUtils = require("@esri/arcgis-to-geojson-utils");
const shapefile = require("shapefile");
const arcgisformer = require("@terraformer/arcgis");
app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.post("/upload", upload.single("file"), async (req, res) => {
  // req.file contains information about the uploaded file
  try {
    //const filePath = path.join(__dirname, req.file.path);
    const filePath = req.file.path;
    // 读取zip文件
    const data = fs.readFileSync(filePath);
    // 解压zip文件
    let zip = await JSZip.loadAsync(data, {
      decodeFileName: function (bytes) {
        const decoder = new TextDecoder("utf8");
        const filenamex = decoder.decode(bytes);
        return filenamex;
      },
    });

    //创建目录
    fs.mkdirSync(filePath + "_");
    // 遍历所有文件，解压到目录
    for (let file in zip.files) {
      let f = zip.files[file];
      if (!f.dir) {
        let content = await f.async("nodebuffer");
        fs.writeFileSync(path.join(filePath + "_", file), content);
      }
      else{
        fs.mkdirSync(path.join(filePath + "_", file));
      }
    }
    // 遍历图层定义，解析shp
    for (let [index, layer] of _dyinfo.layers.entries()) {
      let filename = _importformat[layer.name].name + ".shp";
      let filepath = path.join(filePath + "_", filename);
      let dbfpath = path.join(
        filePath + "_",
        _importformat[layer.name].name + ".dbf"
      );
      if (fs.existsSync(filepath)) {
        /** shappefile库解析，读出来是geojson格式，但是没有Z坐标  */
        let res = await shapefile.read(filepath, dbfpath, {
          encoding: "utf-8",
        });
        const features = [];
        res.features.forEach((feature) => {
          // let geometry = esriUtils.geojsonToArcGIS(ft.geometry);
            // 手工转，待测试
            let geojson = feature.geometry;
            let esrigeo = { spatialReference: { wkid: 4326 } };
            if (geojson.type == "Polygon") {
              esrigeo.rings = geojson.coordinates;
            }
            if (geojson.type == "MultiPolygon") {
              esrigeo.rings = geojson.coordinates[0];
            }
            if (geojson.type == "LineString") {
              esrigeo.paths = [geojson.coordinates];
            }
            if (geojson.type == "MultiLineString") {
              esrigeo.paths = geojson.coordinates;
            }

            esrigeo?.rings?.forEach(ring=>ring.forEach(coord=>{
              coord[2]=0;
            }))
            esrigeo?.paths?.forEach(ring=>ring.forEach(coord=>{
              coord[2]=0;
            }))
            if (geojson.type == "Point") {
              esrigeo = {
                x: geojson.coordinates[0],
                y: geojson.coordinates[1],
              };
            }
            features.push({
              geometry: esrigeo,
              attributes: feature.properties,
            });
        });
        console.log(layer.name);

        // if (layer.name != "D05老旧小区") continue;
        // fs.writeFileSync(layer.name + ".json", JSON.stringify(features));
        /** 更新到arcgis服务器 */
        let batcount = Math.ceil((features.length * 1.0) / 1000);
        for (let i = 0; i < batcount; i++) {
          let upfts = features.slice(1000 * i, 1000 * (i + 1) - 1);
          let response = await rp({
            url: _dyfwlayers + "/" + index + "/addFeatures",
            method: "POST",
            json: true,
            headers: {
              "content-type": "application/x-www-form-urlencoded",
            },
            form: { features: JSON.stringify(upfts), f: "json" },
          });
          console.log(response);
        }
      }
    }
  } catch (e) {
    console.log(e)
    res.send(e);
    return;
  }
  // do something with the uploaded file
  res.send("File uploaded successfully");
});

// 图层信息
const request = require("request");
var rp = require("request-promise");

let _dyinfo;
request.get(_dyfwlayers + "?f=pjson", (err, res, body) => {
  if (err) {
    console.error(err);
    return;
  }
  _dyinfo = JSON.parse(body);
  _dyinfo.layers.forEach((layer) => {
    request.get(_dyfwlayers + `/${layer.id}?f=pjson`, (err, res, body) => {
      if (err) {
        console.error(err);
        return;
      }
      layer.info = JSON.parse(body);
    });
  });
  console.log(_dyinfo);
});
